<template>
  <div>
    <el-form
      class="login-form"
      status-icon
      :rules="loginRules"
      ref="loginForm"
      :model="loginForm"
      label-width="0"
    >
      <!--<el-form-item v-if="tenantMode" prop="tenantId">
    	<el-select class="cellbac"
		    v-model="loginForm.tenantId"
        autocomplete="off"
		    filterable
		    remote
		    reserve-keyword
		    :popper-append-to-body="false"
		    placeholder="请输入关键词"
		    :remote-method="remoteMethod"
		    @change="remoteChange"
		    :loading="loading">
		    <el-option
		      v-for="item in options"
		      :key="item.tenantId"
		      :label="item.tenantName"
		      :value="item.tenantId">
		    </el-option>
		    <i slot="prefix"
           class="icon-quanxian"></i>
		  </el-select>
    </el-form-item>-->
      <el-form-item prop="username">
        <el-input
          size="small"
          class="cellbac"
          @keyup.enter.native="handleLogin"
          v-model="loginForm.username"
          autocomplete="off"
          :placeholder="$t('login.username')"
        >
          <i slot="prefix" class="icon-yonghu"></i>
        </el-input>
      </el-form-item>
      <el-form-item prop="password">
        <el-input
          size="small"
          class="cellbac"
          @keyup.enter.native="handleLogin"
          :type="passwordType"
          v-model="loginForm.password"
          autocomplete="new-password"
          :placeholder="$t('login.password')"
        >
          <i
            class="el-icon-view el-input__icon"
            slot="suffix"
            @click="showPassword"
          ></i>
          <i slot="prefix" class="icon-mima"></i>
        </el-input>
      </el-form-item>
      <el-form-item v-if="captchaMode" prop="code">
        <el-row :span="24">
          <el-col :span="16" class="cellbac">
            <el-input
              size="small"
              @keyup.enter.native="handleLogin"
              v-model="loginForm.code"
              autocomplete="off"
              :placeholder="$t('login.code')"
            >
              <i slot="prefix" class="icon-yanzhengma" />
            </el-input>
          </el-col>
          <el-col :span="8" class="cellbac">
            <div class="login-code">
              <img
                :src="loginForm.image"
                class="login-code-img"
                @click="refreshCode"
              />
            </div>
          </el-col>
        </el-row>
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          size="small"
          @click.native.prevent="handleLogin"
          class="login-submit"
          >{{ $t("login.submit") }}
        </el-button>
      </el-form-item>
    </el-form>
    <div
      tabindex="-1"
      class="el-message-box__wrapper"
      style="z-index: 2250"
      v-show="showSelectTenant"
    >
      <div class="el-message-box">
        <div class="el-message-box__header">
          <div class="el-message-box__title">
            <span>请选择学校或机构</span>
          </div>
        </div>
        <div class="el-message-box__content">
          <div class="el-message-box__container">
            <div class="el-message-box__message">
              <p>
                <el-card
                  class="box-card"
                  style="height: 320px; overflow-y: auto"
                >
                  <div
                    v-for="o in userTenantList"
                    :key="o.tenantId"
                    class="text item ulist"
                    @click="selectedTenent(o.tenantId)"
                  >
                    <el-link type="primary" :underline="false">{{
                      o.tenantName
                    }}</el-link>
                    <i class="el-icon-arrow-right ulist_right"></i>
                  </div>
                </el-card>
              </p>
            </div>
          </div>
        </div>
      </div>
    </div>
    <div
      class="v-modal"
      tabindex="0"
      style="z-index: 2240"
      v-show="showSelectTenant"
    ></div>
  </div>
</template>

<script>
import { mapGetters } from "vuex";
import website from "@/config/website";
import { getCaptcha } from "@/api/user";
import { getTopUrl } from "@/util/util";
import { info } from "@/api/system/tenant";
import { findTenList, getTenList, changeTenant } from "@/api/user";
import { Message } from "element-ui";
export default {
  name: "userlogin",
  data() {
    return {
      options: [],
      list: [],
      loading: false,
      tenantMode: website.tenantMode,
      captchaMode: false,
      showSelectTenant: false,
      tenantName: "",
      userTenantList: [],
      ctrUser: {},
      loginForm: {
        //租户ID
        tenantId: "",
        //用户名
        username: "",
        //密码
        password: "",
        //账户类型
        type: "account",
        //验证码的值
        code: "",
        //验证码的索引
        key: "",
        //预加载白色背景
        image:
          "",
      },
      loginRules: {
        tenantId: [
          { required: false, message: "请输入租户ID", trigger: "click" },
        ],
        username: [
          { required: true, message: "请输入用户名", trigger: "blur" },
        ],
        password: [
          { required: true, message: "请输入密码", trigger: "blur" },
          { min: 1, message: "密码长度最少为6位", trigger: "blur" },
        ],
      },
      passwordType: "password",
    };
  },
  created() {
    //this.getTenant();
    //this.refreshCode();
  },
  mounted() {
    const jizhu_user = localStorage.getItem("jizhu_user");
    if (jizhu_user) {
      const user = JSON.parse(jizhu_user);
      //this.loginForm.tenantId = user.tenantId;
      //用户名
      this.loginForm.username = user.username;
      //密码
      this.loginForm.password = user.password;
      //this.tenantName = user.tenantName;
      //this.remoteMethod(user.tenantName);
    }
  },
  computed: {
    ...mapGetters(["tagWel"]),
  },
  props: [],
  methods: {
    remoteMethod(query) {
      if (query !== "") {
        this.loading = true;
        findTenList(query).then((res) => {
          this.loading = false;
          this.options = res.data.data;
        });
      } else {
        this.options = [];
      }
    },
    remoteChange(val) {
      var option = this.options.filter((item) => {
        return item.tenantId == val;
      });
      this.tenantName = option[0].tenantName;
    },
    refreshCode() {
      getCaptcha().then((res) => {
        const data = res.data.data;
        this.loginForm.key = data.key;
        this.loginForm.image = data.image;
      });
    },
    showPassword() {
      this.passwordType === ""
        ? (this.passwordType = "password")
        : (this.passwordType = "");
    },
    handleLogin() {
      /*if(!this.loginForm.tenantId) {
	    		 Message({
			      message: "请选择所属学校或机构",
			      type: 'error'
			    })
	    		 return;
	    	}*/
      this.$refs.loginForm.validate((valid) => {
        if (valid) {
          const loading = this.$loading({
            lock: true,
            text: "登录中,请稍后。。。",
            spinner: "el-icon-loading",
          });
          const uer = this.loginForm;
          this.$store
            .dispatch("LoginByUsername", this.loginForm)
            .then((res) => {
              const { tenantId, username, password } = uer;
              const { account } = res;
              this.ctrUser = res;
              const loginfo = res;
              localStorage.setItem(
                "jizhu_user",
                JSON.stringify({ username: username, password: password })
              );
              getTenList({ account }).then((rep) => {
                const tenList = rep.data.data;
                this.userTenantList = rep.data.data;
                if (tenList && tenList.length > 1) {
                  loading.close();
                  const _this = this;
                  setTimeout(function () {
                    loading.close();
                    _this.showSelectTenant = true;
                  }, 500);
                } else {
                  const param = {
                    roles: loginfo.authority.split(","),
                    oauthId: loginfo.oauthId,
                    user: {
                      id: loginfo.userId,
                      tenantId: tenList[0].tenantId,
                      name: loginfo.userName,
                      realName: loginfo.userName,
                      account: loginfo.account,
                      gradeId: loginfo.gradeId,
                      roleId: loginfo.roleId,
                    },
                  };
                  const _this = this;
                  changeTenant(param).then((res) => {
                    const user = res.data.data;
                    user.changeTenant = "changeTenant";
                    _this.$store.dispatch("LoginByPhone", user);
                    loading.close();
                    _this.$router.push({ path: this.tagWel.value });
                  });
                }
              });
            })
            .catch(() => {
              loading.close();
            });
        }
      });
    },
    selectedTenent(tenantId) {
      const loginfo = this.ctrUser;
      const param = {
        roles: loginfo.authority.split(","),
        oauthId: loginfo.oauthId,
        user: {
          id: loginfo.userId,
          tenantId: tenantId,
          name: loginfo.userName,
          realName: loginfo.userName,
          account: loginfo.account,
          gradeId: loginfo.gradeId,
          roleId: loginfo.roleId,
        },
      };
      const _this = this;
      changeTenant(param).then((res) => {
        const user = res.data.data;
        user.changeTenant = "changeTenant";
        _this.$store.dispatch("LoginByUsername", user);
        _this.$router.push({ path: this.tagWel.value });
      });
    },
    getTenant() {
      let domain = getTopUrl();
      // 临时指定域名，方便测试
      //domain = "https://bladex.vip";
      info(domain).then((res) => {
        const data = res.data;
        if (data.success && data.data.tenantId) {
          this.tenantMode = false;
          this.loginForm.tenantId = data.data.tenantId;
        }
      });
    },
  },
};
</script>

<style>
.cellbac.el-select {
  width: 100%;
}
/deep/ .el-select-dropdown {
  .el-scrollbar {
    .el-scrollbar__view {
      .el-select-dropdown__item {
        display: inline-block;
        margin-bottom: 12px;
      }
    }
  }
  /deep/.el-select-dropdown__wrap.el-scrollbar__wrap {
    margin-bottom: 0 !important;
  }
  .ulist {
    border-bottom: 1px solid #ccc;
    line-height: 40px;
    cursor: pointer;
  }
  .ulist_right {
    display: inline-block;
    float: right;
    margin-top: 18px;
  }
}
</style>
